/**
 * 
 */
package com.deep.test.collection;

/**
 * @author HDP23
 *
 */
public class BitMap {
	 private final static int ADDRESS_BITS_PER_WORD = 5;
	private final int[] bitMap;
	/**
	 * size for map
	 */
	private final int size;
	public BitMap(final int size){
		this.size=size;
		int sLen = (size%32)==0?size>>ADDRESS_BITS_PER_WORD:size>>ADDRESS_BITS_PER_WORD +1;
		this.bitMap= new int[sLen];
	}
	/**
	 * real index for bitMap
	 * @param number
	 * @return
	 */
	private static int index(final int number){
		return number>>ADDRESS_BITS_PER_WORD;
	}
	/**
	 * position for number in bitMap's int value
	 * @param number
	 * @return
	 */
	private static int position(final int number){
		return number%32;
	}
	/**
	 * add a int number
	 * @param number
	 */
	public void add(int number){
		putBitMap(index(number),position(number));
	}
	/**
	 * 存储数值到bitmap
	 * @param index
	 * @param position
	 */
	private void putBitMap(int index, int position) {
		int bit = bitMap[index]|(1<<position);
		bitMap[index]=bit;
	}
	/**
	 * 是否存在index
	 * @param index
	 * @return
	 */
    public  boolean isIndex(int index){
    	if(index>size){
    		return false;
    	}
    	int bit = bitMap[index(index)]>>position(index)&0x001;
		return bit==1;
    }	
	public static void main(String[] args) {
		BitMap bitMap = new BitMap(100);
		for(int i=0;i<10;i++){
			bitMap.add(i);
		}
		System.out.println(bitMap.isIndex(5));
	}

}
